import os
from werkzeug.utils import secure_filename
from app.utils.errors import ValidationError
from app import logger

def allowed_file(filename, allowed_extensions):
    """检查文件扩展名是否允许"""
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in allowed_extensions

def process_file(file, upload_folder, allowed_extensions):
    """处理上传的文件
    
    Args:
        file: 上传的文件对象
        upload_folder: 文件保存目录
        allowed_extensions: 允许的文件扩展名集合
    
    Returns:
        str: 保存的文件路径
    """
    if not file:
        raise ValidationError("No file provided")
        
    filename = secure_filename(file.filename)
    if not allowed_file(filename, allowed_extensions):
        raise ValidationError(f"File type not allowed. Allowed types: {', '.join(allowed_extensions)}")
    
    # 确保上传目录存在
    os.makedirs(upload_folder, exist_ok=True)
    
    # 保存文件
    file_path = os.path.join(upload_folder, filename)
    file.save(file_path)
    logger.info(f"File saved: {file_path}")
    
    return file_path

def process_text_file(file_path, encoding='utf-8'):
    """处理文本文件
    
    Args:
        file_path: 文件路径
        encoding: 文件编码，默认 utf-8
    
    Returns:
        str: 文件内容
    """
    try:
        with open(file_path, 'r', encoding=encoding) as f:
            return f.read()
    except UnicodeDecodeError:
        # 如果 UTF-8 解码失败，尝试其他编码
        try:
            with open(file_path, 'r', encoding='gbk') as f:
                return f.read()
        except UnicodeDecodeError as e:
            logger.error(f"Failed to decode file {file_path}: {str(e)}")
            raise ValidationError("Unable to decode file content")
    except Exception as e:
        logger.error(f"Error processing file {file_path}: {str(e)}")
        raise ValidationError(f"Error processing file: {str(e)}")

def save_text_content(content, file_path):
    """保存文本内容到文件
    
    Args:
        content: 要保存的文本内容
        file_path: 保存的文件路径
    """
    try:
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(content)
        logger.info(f"Content saved to file: {file_path}")
    except Exception as e:
        logger.error(f"Error saving content to file {file_path}: {str(e)}")
        raise ValidationError(f"Error saving content: {str(e)}")

def save_file(file, upload_folder):
    """
    兼容性函数，调用 process_file
    
    Args:
        file: 上传的文件对象
        upload_folder: 文件保存目录
    
    Returns:
        str: 保存的文件路径
    """
    from flask import current_app
    return process_file(
        file=file,
        upload_folder=upload_folder,
        allowed_extensions=current_app.config.get('ALLOWED_EXTENSIONS', set())
    ) 